﻿using Arction.Wpf.Charting;
using Arction.Wpf.Charting.Axes;
using Arction.Wpf.Charting.Views.ViewXY;
using HighThroughput.Common;
using HighThroughput.ShareData;
using Microsoft.Win32;
using Newtonsoft.Json;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using OSSUtility;
using OSSUtility.Charts;
using Ozone.BLL;
using Ozone.Device;
using Ozone.Models;
using Ozone.Views.Widget;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Ozone.Views.Curve
{
    /// <summary>
    /// UCLineChart.xaml 的交互逻辑
    /// </summary>
    public partial class UCLineChart : UserControl
    {
        public ModuleLineChart moduleLineChart = null;
        List<string> lstDataIDs = new List<string>();
        List<string> lstTitle = new List<string>();
        List<DataHisModel> lstDataHis = new List<DataHisModel>();

        string CHName = "M";
        string FDataID = "";
        string minY = "0", maxY = "20";

        public UCLineChart()
        {
            InitializeComponent();
            moduleLineChart = new ModuleLineChart("", gridLinechart);
            moduleLineChart.setLegendBoxesShow(true);
            moduleLineChart.setBackground(Brushes.Black);
            moduleLineChart.setColor(Colors.Black, Colors.SlateGray);

            moduleLineChart.LegendBoxPosition(3);

            Init(this.Tag.ToString()) ;
        }

        public void setTitle(string title)
        {
            lblTitle.Content = title;
        }

        public void Init(string DataID)
        {
            FDataID = DataID;

            getParam();

            if (maxY != "")
            {
                txtTempMin.Text = minY;
                txtTempMax.Text = maxY;

                setYRangPro(Utility.str2int(txtTempMin.Text), Utility.str2int(txtTempMax.Text));
            }

            Start();
        }

        public void Start()
        {
            RefreshLineThread();
        }

        public void Stop()
        {
            bRunFlag = false;
        }

        public void addLine(string plsTitle, string plsTag, int nLineColorIndex)
        {
            moduleLineChart.addLine(plsTitle, plsTag, nLineColorIndex);

            lstTitle.Add(plsTitle);
            lstDataIDs.Add(plsTag);
        }

        private void TextBoxTRang_LostFocus(object sender, RoutedEventArgs e)
        {
            setYRangPro(Utility.str2int(txtTempMin.Text), Utility.str2int(txtTempMax.Text));

            saveParam();

        }

        public void setYRangPro(int min, int max)
        {
            moduleLineChart.setYRang(min, max);
        }

        bool bRunFlag = false;
        DateTime DTStart;
        private void RefreshLineThread()
        {
            DTStart = DateTime.Now;
            bRunFlag = true;

            Task.Run(() =>
            {
                while (bRunFlag)
                {
                    Thread.Sleep(1000);
                    refreshLineData();

                }
            });

        }

        public void setEnabled(bool bEnabled)
        {
            if (!bEnabled)
            {
                bRunFlag = false;
                this.IsEnabled = false;
            }
        }

        private void refreshLineData()
        {
            if (ReadData.Entity.curRealData == null)
                    return;

            //this.Dispatcher.Invoke(new Action(
            //    delegate
            //    {
            //        try
            //        {
            //            string sTest = "";
            //            DataHisModel dataHis = new DataHisModel();
            //            dataHis.FDateTime = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            //            for (int i = 0; i < lstDataIDs.Count; i++)
            //            {

            //                double dVal = Utility.str2double(ReadData.Entity.curRealData.rd_EMCData.getValByID(lstDataIDs[i]));
            //                AddPoint(moduleLineChart, dVal, lstDataIDs[i]);

            //                dataHis.lstData.Add(dVal);

            //                sTest += "|" + dVal.ToString();
            //            }

            //            lstDataHis.Add(dataHis);

            //        }
            //        catch (Exception ex)
            //        {

            //        }
            //    }
            //           )
            //       );
        }

        private void AddPoint(ModuleLineChart mlc, double v, string tag)
        {
            try
            {
                SeriesPoint[] aPoints = new SeriesPoint[1];
                aPoints[0].X = mlc.DateTimeToAxisValue(DateTime.Now);
                aPoints[0].Y = v;
                mlc.AddPoints(tag, aPoints);

                LightningChart cartesianChart = mlc.getCartesianChart();
                ViewXY chartView = cartesianChart.ViewXY;
                AxisX axisX = chartView.XAxes[0];
                axisX.SetRange(mlc.DateTimeToAxisValue(DTStart)
                         , mlc.DateTimeToAxisValue(DateTime.Now));

            }
            catch (Exception ex)
            {
                Log.writeLog("UCAppCurve-AddPoint", ex.Message);
            }
        }

        private void getParam()
        {

            S10SetupPanelParam setupParam = ChartParamBLL.get();
            string val = setupParam.getVal(FDataID);
            string[] arV = val.Split(',');
            if (arV.Length == 2)
            {
                minY = arV[0];
                maxY = arV[1];
            }

        }

        private void saveParam()
        {
            S10SetupPanelParam setupParam = ChartParamBLL.get();
            string val = txtTempMin.Text + "," + txtTempMax.Text;
            setupParam.setVal(FDataID, val);
            ChartParamBLL.save(setupParam);
        }

      

        private void btnExport_Click(object sender, RoutedEventArgs e)
        {



            string filepath = "";
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Title = "保存EXCEL文件";
            dlg.FileName = lblTitle.Content + " " + System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls"; // Default file name
            dlg.DefaultExt = ".xls"; // Default file extension
            dlg.Filter = "Excel文件|*.xls"; // Filter files by extension
                                          //dlg.InitialDirectory = initFolder;

            if (dlg.ShowDialog() == true)
            {
                filepath = dlg.FileName;
            }
            else
            {
                return;
            }


            _ = WindowWaiting.ShowWaitDlgAsync(this, true, "正在生成EXCEL文件，请稍候...");


            _ = toExcelAsync(filepath);
        }


        private async Task toExcelAsync(string fileName)
        {

            await Task.Run(() =>
            {
                this.Dispatcher.Invoke(delegate ()
                {

                    try
                    {
                        saveToExce1Pro(fileName);//加载数据，比如查询数据库什么的
                        _ = WindowWaiting.ShowWaitDlgAsync(this, false);
                    }
                    catch (Exception)
                    {

                    }
                });
            });

        }

        //快速导出
        public void saveToExce1Pro(string FilePath)
        {

            try
            {
                // 创建Excel表格
                IWorkbook workbook = new XSSFWorkbook();
                ISheet sheet = workbook.CreateSheet("Sheet1");
                // 写入多行数据
                IRow rowHeader = sheet.CreateRow(0);
                rowHeader.CreateCell(0).SetCellValue("序号");
                rowHeader.CreateCell(1).SetCellValue("时间");
                for (int i = 0; i < lstTitle.Count; i++)
                {
                    rowHeader.CreateCell(2 + i).SetCellValue(lstTitle[i]);
                }

                //填充数据
                for (int i = 0; i < lstDataHis.Count; i++)
                {
                    DataHisModel dp = lstDataHis[i];

                    if (dp == null)
                        continue;

                    IRow row = sheet.CreateRow(i + 1);
                    row.CreateCell(0).SetCellValue(i + 1);
                    row.CreateCell(1).SetCellValue(dp.FDateTime);


                    for (int j = 0; j < dp.lstData.Count; j++)
                    {
                        row.CreateCell(2 + j).SetCellValue(dp.lstData[j]);
                    }
                }

                // 保存Excel文件
                FileStream fileStream = new FileStream(FilePath, FileMode.Create, FileAccess.Write);
                workbook.Write(fileStream);
                fileStream.Close();

                MessageBox.Show("导出成功!", "提示",
                         MessageBoxButton.OK, MessageBoxImage.Information);

            }

            catch (Exception e)
            {
                Log.writeLog("saveToExce", e.Message);
                MessageBox.Show("导出失败，请安装OFFICE软件!", "提示",
                        MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
    }
}
